package su.mvc.util;


import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import org.apache.log4j.Logger;
import su.mvc.model.MenuItem;
import su.mvc.model.PageContent;
import su.mvc.service.gui.MenuService;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class InitialModelCreatorListener implements ServletContextListener {

    final static Logger LOG = Logger.getLogger(InitialModelCreatorListener.class);

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ObjectifyService.register(MenuItem.class);
        ObjectifyService.register(PageContent.class);
        Objectify ofy = ObjectifyService.begin();

        try {
            ofy.get(MenuItem.class, MenuService.TOP_MENU_ITEM).getKey();
        } catch (NotFoundException e) {
            MenuItem topMenuItem = new MenuItem();
            topMenuItem.setId(MenuService.TOP_MENU_ITEM);
            topMenuItem.setName("Top");
            Key key = ofy.put(topMenuItem);

            PageContent pageContent = new PageContent();
            pageContent.setId(MenuService.TOP_PAGE_ITEM);

            topMenuItem.setKey(key);
            topMenuItem.setContentId(pageContent.getId());
            ofy.put(topMenuItem, pageContent);
            
            LOG.warn("No TOP menu item -- new one has been created");
        }

    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //
    }
}
